/*
 * @Author: Wuyi
 * @Date: 2021-01-23 15:10:06
 * @LastEditTime: 2021-05-03 14:32:55
 * @LastEditors: zy
 * @Description: 书籍关联可视化
 */
import * as d3 from 'd3'
import { cluster } from 'd3'
export class Related {
  chart = {}
  color = d3.scaleOrdinal(d3.schemeCategory10)

  constructor (divId) {
    this.divId = divId
  }

  setData (data) {
    this.data = data
  }

  render () {
    this.initChart()
    this.initLayout()
  }

  initChart () {
    this.chart.padding = {
      left: 20,
      right: 50,
      top: 20,
      bottom: 20
    }
    this.chart.divHeight = document.getElementById(this.divId).offsetHeight -
      this.chart.padding.top -
      this.chart.padding.bottom
    this.chart.divWidth = document.getElementById(this.divId).offsetWidth -
      this.chart.padding.left -
      this.chart.padding.right

    this.chart.svg = d3
      .select('#' + this.divId)
      .append('svg')
      .attr('width', this.chart.divWidth)
      .attr('height', this.chart.divHeight)
      .append('g')
      .attr('transform', 'translate(40,0)')
      .attr('class', 'svg_chart')
  }

  initLayout () {
    this.chart.luster = d3.cluster()
      .size([this.chart.divWidth, this.chart.divHeight - 200])
  }

  drawCluster () {
    let nodes = cluster.nodes(this.data)
    let links = cluster.links(nodes)

    nodes[20].y = nodes[20].y * -1 + 300

    console.log(nodes)
    console.log(links)

    this.chart.link = this.chart.svg.selectAll('.link')
      .data(links)
      .enter()
      .append('path')
      .attr('class', 'link')
      .attr('d', function (d) {
        let start = {
          x: d3.pointRadial(d.x, d.y)[0],
          y: d3.pointRadial(d.x, d.y)[1]
        }
        let end = {
          x: d3.pointRadial(d.parent.x, d.parent.y)[0],
          y: d3.pointRadial(d.parent.x, d.parent.y)[1]
        }
        return diagonal(start, end)
      })

    this.chart.node = this.chart.svg.selectAll('.node')
      .data(nodes)
      .enter()
      .append('g')
      .attr('class', 'node')
      .attr('transfrom', function (d) {
        return 'translate(' + d.y + ',' + d.x + ')'
      })

    this.chart.node.append('circle')
      .attr('r', 5)

    this.chart.node.append('text')
      .attr('dx', function (d) {
        return d.children ? -8 : 8
      })
      .attr('dy', 3)
      .style('text-anchor', function (d) {
        return d.children ? 'end' : 'start'
      })
      .text(function (d) {
        return d.name
      })
    function diagonal (s, d) {
      let path = `M ${s.x} ${s.y}
              C ${s.x} ${(s.y + d.y) / 2},
                ${d.x} ${(s.y + d.y) / 2},
                ${d.x} ${d.y}`
      return path
    }
  }
}
